<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Redis;

class ApiCheck
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle(Request $request, Closure $next)
    {
        $apiKey = env('API_KEY');
        $data = $request->all();
        if (!isset($data['sign'])) {
            return response()->json(['code'=>803,'msg'=>'非法请求参数']);
        }
        $sign = $data['sign'];    // 取出sign
        unset($data['sign']);     // 删除数组中的sign
        unset($data['s']);        // 去掉's' 's'键参数为 api路由
        $data['key'] = $apiKey;
        ksort($data);             // 对数组的键进行排序
        $data = http_build_query($data); // 转化为URL请求字符串
        $newSign = md5($data);

        // 验证sign签名
        if ($newSign != $sign) {
            return response()->json(['code'=>801,'msg'=>'非法的接口请求']);
        };

        if (Redis::get($sign)) {
            return response()->json(['code'=>802,'msg'=>'请勿重复请求接口']);
        }

        Redis::setex($sign, 60, 1); // 设置$sign为键 1为值    保存时间60s

        return $next($request);
    }
}
